<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="跨域的原理及解决方案, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>跨域的原理及解决方案 | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/12.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">跨域的原理及解决方案</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Javascript/">
                                <span class="chip bg-color">Javascript</span>
                            </a>
                        
                            <a href="/tags/Ajax/">
                                <span class="chip bg-color">Ajax</span>
                            </a>
                        
                            <a href="/tags/Jsonp/">
                                <span class="chip bg-color">Jsonp</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                技术分享
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-16
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    1.9k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、何为跨域">一、何为跨域</h2>
<p>广义的跨域是指一个域下的文档和脚本试图请求另一个域下的资源。<br>
举<img class="emoji" draggable="false" alt="🌰" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f330.png"/></p>
<ol>
<li>资源跳转： A链接、重定向、表单提交</li>
<li>资源嵌入：<code>&lt;link&gt;、&lt;script&gt;、&lt;img&gt;、&lt;frame&gt;</code>等DOM标签，还有样式中<code>background:url()、@font-face()</code>等文件外链</li>
<li>脚本请求： Js发起的Ajax请求、DOM和Js对象的跨域操作等<br>
而我们常说的跨域，是指浏览器不能执行其他网站的脚本。它是由于浏览器的<strong>同源策略</strong>限制造成的。</li>
</ol>
<p><strong>同源策略：</strong> 浏览器对JS实施的安全限制，只要“协议、域名、端口号”有任何一个不同，都被当做是不同的域。缺少哦同源策略，浏览器很容易受到<code>XSS、CSFR</code>等攻击<img class="emoji" draggable="false" alt="‼️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/203c.png"/></p>
<p><img class="emoji" draggable="false" alt="❌" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/274c.png"/>同源策略限制以下几种行为：</p>
<ul>
<li><code>cookie、LocalStorage和IndexDB</code>无法读取</li>
<li><code>DOM</code> 和 <code>JS</code>对象无法获得</li>
<li><code>AJAX</code>请求不能发送</li>
</ul>
<blockquote>
<p>关于XSS和CSRF, cc之后会专门整理关于网络安全防范的文章~</p>
</blockquote>
<h2 id="二、跨域的原理">二、跨域的原理</h2>
<p>跨域的原理就是通过各种方式，避开浏览器的安全限制。</p>
<h2 id="三、跨域的解决方案">三、跨域的解决方案</h2>
<p>我们可以通过多种方式实现跨域，常见的如下七种，大致分为<code>iframe</code>、<code>api</code>跨域：</p>
<ol>
<li>
<p><strong>JSONP（JSON with Padding）</strong>: 开发人员创造的一种非官方跨域数据交互协议。Ajax请求受到同源策略的影响，不允许进行跨域请求，而<code>script</code>标签src属性中的链接却可以访问跨域的js脚本，web页面调用JS文件不受浏览器同源策略的限制。利用这个特性，服务端不再返回json格式的数据，而是返回一段调用某个函数的js代码，在src中进行调用，这样就可以实现跨域。 <strong>jsonp通过动态创建script，再请求一个带参网址实现跨域通信，解决老版本浏览器跨域数据访问问题</strong>，流程如下：</p>
<p><img class="emoji" draggable="false" alt="1️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/31-20e3.png"/>. 首先前端设置好回调参数，并将其作为<code>URL</code>的参数<br>
<img class="emoji" draggable="false" alt="2️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/32-20e3.png"/>. 服务器端收到请求之后，通过该参数获取到回调函数名，并将数据放在参数中返回<br>
<img class="emoji" draggable="false" alt="3️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/33-20e3.png"/>. 收到结果后因为是<code>script</code>标签，所以浏览器当做脚本运行。</p>
</li>
</ol>
<p>详细说一下前端实现JSONP：</p>
<ul>
<li>原生实现</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">var script = document.createElement('script')
script.type = 'text/javascript'

// 传参一个回调函数名给后端，方便后端返回时执行这个在前端定义的回调函数
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback'
document.head.appendChild(script)

// 回调执行函数
function handleCallback(res){
  alert(JSON.stringify(res))
}
</code></pre>
<p>服务端返回如下（返回时执行全局函数）：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">handleCallback({"status": true, "user": "admin"})
</code></pre>
<ul>
<li>Jquery / Ajax</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">$.ajax({
  url: 'http://www.domain2.com:8080/login',
  type: 'get',
  dataType: 'jsonp', // 格式方法为jsonp
  jsonpCallback: "handleCallback", // 自定义回调函数名
  data: {}
});
</code></pre>
<ul>
<li>Vue.js</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">this.$http.jsonp('http://ww.domain2.com:8080/login',{
  params: {},
  jsonp: 'handleCallback'
}).then((res) =>{
  console.log(res)
})
</code></pre>
<p>后端Node.js代码示例：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var querystring = require('querystring')
var http = require('http')
var server = http.createServer()

server.on('request', function(req, res){
  var params = qs.parse(req.url.split('?')[1])
  var fn = params.callback 
   
  // jsonp返回设置 
  res.writeHead(200, {'Content-Type': 'text/javascript'})
  res.write(fn + '(' + JSON.stringify(params) + ')')

  res.end()
});
server.listen('8080')
console.log('Server is running at port 8080 ...')
</code></pre>
<h2 id="常见的手写jsonp算法示例：">常见的手写jsonp算法示例：</h2>
<p><strong>jsonp原理：</strong><br>
借助script标签不受同源策略限制的特点，把script标签的src指向请求的服务端地址。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function jsonp(url, data = {}, callback = 'callback') {
   // 处理json对象，将参数拼接为url
   data.callback = callback
   let params = []
   for(let key in data) {
     params.push(key + '=' + data[key])
   }
   let script = document.createElement('script')
   script.src = url + '?' + params.join('&')
   document.body.appendChild(script)

   return new Promise((reslove, reject) => {
     window[callback] = (data) => {
       try {
         reslove(data)
       } catch (e) {
         reject(e)
       } finally {
         // 移除script元素
         script.parentNode.removeChild(script)
       }
     }
   })
}

// 使用jsonp请求数据
jsonp('http://dsbcjkxs.index', {
  page: 1,
  cate: 'recommend',
}, 'jsonpcallback').then(data => {
  console.log(data)
})
</code></pre>
<ol start="2">
<li>
<p><strong>CORS跨域资源共享(Cross-origin resource sharing)</strong>：是一个W3C标准，允许浏览器向跨源服务器发送<code>XMLHTTP Request</code>请求，从而克服了ajax只能同源使用的限制，<strong>实现CORS的关键是服务器，只要服务器实现了CORS接口，就可以进行跨源通信。</strong></p>
<ol>
<li>
<p>前端的逻辑十分简单，正常发起ajax即可，成功的关键在于服务器<code>Access-Control-Allow-Origin</code>是否包含请求页面的域名，若要携带cookie请求，前后端都需要设置。如果不包含的话，浏览器将认为这是一次失败的异步请求，将会调用<code>xhr.onerror</code>中的函数。整个Cors的通信过程都是浏览器自动完成，不需要用户参与。</p>
</li>
<li>
<p>CORS使用简单，支持<code>POST</code>方式，但是存在兼容问题</p>
</li>
<li>
<p>浏览器将CORS请求分为两类：<strong>简单请求</strong>和<strong>非简单请求</strong>,浏览器对于这两种的处理不同</p>
</li>
<li>
<p>简单请求（simple request）需满足两大条件：<br>
1） 请求方法是三种之一：<code>HEAD、GET、POST</code><br>
2） HTTP的头部信息不超过以下几个字段：<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Accept<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Accept-Language<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Content-Language<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Last-Event-ID<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Content-Type: 只限于三个值<code>application/x-www-form-urlencoded</code>、<code>multipart/form-data</code>、<code>text-plain</code></p>
</li>
<li>
<p>非简单请求(not-so-simple request)：<br>
1）对浏览器有特殊要求的请求，<code>PUT、DELETE</code>或者字段为<code>Content-Type: application/json</code>类型的请求<br>
2）在正式通信之前，会增加一次HTTP查询请求，成为**“预检”**请求（<code>preflight</code>）,请求方法是<code>OPTIONS</code><br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Origin: 表示请求来自哪个源<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/>Access-Control-Request-Method: 必选，列出CORS请求会用到哪些HTTP方法<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Access-Control-Request-Headers: 逗号分隔，指定浏览器CORS请求会额外发送的头信息字段</p>
</li>
<li>
<p>如果服务器同意本次请求，返回的响应会多出几个头信息字段：</p>
<p><img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Access-Control-Allow-Origin: 返回Origin的字段或*<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Access-Control-Allow-Credentials: 可选, bool值，表示是否发送cookie<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> Access-Control-Expose-Headers</p>
</li>
<li>
<p>举<img class="emoji" draggable="false" alt="🌰" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f330.png"/>Vue框架中的设置：<br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> axios设置： <code>axios.defaults.withCredentials = true</code><br>
<img class="emoji" draggable="false" alt="🔻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f53b.png"/> vue-resource设置： <code>Vue.http.options.credentials = true</code></p>
<p><img class="emoji" draggable="false" alt="➡️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/27a1.png"/> <a href="www.ruanyifeng.com/blog/2016/04/cors.html">阮一峰——《跨域资源共享CORS详解》</a></p>
</li>
</ol>
</li>
<li>
<p><strong>代理跨域</strong>：把跨域的请求操作发送给后端，让后端帮忙代理请求,包括<code>nginx</code>代理跨域、<code>nodejs</code>中间件代理跨域、<code>webSocket</code>协议跨域</p>
</li>
<li>
<p><strong>document.domain + iframe跨域</strong>：两个页面都通过js强制设置<code>document.domain</code>为基础主域，就实现了同域。【此方案仅限主域相同，子域不同的跨域应用场景】</p>
</li>
<li>
<p><strong>location.hash + iframe跨域</strong> ：a若要与b跨域相互通信，通过中间页c来实现，c与a同域，可以通过parent.parent来访问a页面的所有对象。三个页面，不同域之间利用iframe的<code>location.hash</code>传值，相同域之间直接js访问来通信。</p>
</li>
<li>
<p><strong><a href="http://window.name" target="_blank" rel="noopener">window.name</a> + iframe跨域</strong> ：通过iframe的<code>src</code>属性由外域转向本地域，跨域数据即由iframe的<code>window.name</code>从外域传递到本地域，巧妙地绕过了浏览器的跨域访问限制，但是又是安全操作。window.name属性的独特之处在于，name值在不同的页面（甚至不同域名）加载后依旧存在，并且可以支持非常长的name值（2MB）</p>
</li>
<li>
<p><strong>postMessage跨域</strong>：它是HTML5 XMLHttpRequest Level 2中的API，可以跨域操作的window属性之一，主要解决：<br>
1）页面和其打开的新窗口的数据传递<br>
2）多窗口之间的消息传递<br>
3）页面与嵌套的iframe消息传递<br>
4）上述三个场景的跨域数据传递</p>
</li>
</ol>
<p><strong>JSONP和CORS的对比<img class="emoji" draggable="false" alt="🍻" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f37b.png"/>：</strong></p>
<ul>
<li>使用目的相同，但是CORS比JSONP强大</li>
<li>JSONP只支持<code>GET</code>请求，CORS支持所有类型的HTTP请求</li>
<li>JSONP的优势在于支持老式浏览器，以及可以向不支持CORS的网站请求数据</li>
</ul>
<p>在众多跨域的解决方案中，最常见的还是前三种解决方案<img class="emoji" draggable="false" alt="😆" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f606.png"/></p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/16/16-kua-yu-de-yuan-li-ji-jie-jue-fang-an/">https://caseylu.gitee.io/2020/03/16/16-kua-yu-de-yuan-li-ji-jie-jue-fang-an/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Javascript/">
                                    <span class="chip bg-color">Javascript</span>
                                </a>
                            
                                <a href="/tags/Ajax/">
                                    <span class="chip bg-color">Ajax</span>
                                </a>
                            
                                <a href="/tags/Jsonp/">
                                    <span class="chip bg-color">Jsonp</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-16T17-23-07',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/19/17-javascript-bi-shi-shua-ti-xiao-jie-san/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/20.jpg" class="responsive-img" alt="Javascript笔试刷题小结（三）">
                        
                        <span class="card-title">Javascript笔试刷题小结（三）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            生命不息，刷题不止，hhhhhhhhhh …  可爱的我又来了
1. Leetcode 1013. 将数组分成和相等的三个部分
**思路一：**最开始看到题目的时候cc是这么想的，既然能分成三个部分，不妨先计算每个部分的和，然后只要能成功地
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AC%94%E8%AF%95%E9%9D%A2%E8%AF%95/" class="post-category">
                                    笔试面试
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/Leetcode/">
                        <span class="chip bg-color">Leetcode</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/15/15-websocket-yuan-li-shi-xian-he-ying-yong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/4.jpg" class="responsive-img" alt="WebSocket的原理、实现和应用">
                        
                        <span class="card-title">WebSocket的原理、实现和应用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            webSocket是一项可以让服务器将数据主动推送给客户端的技术，无论前后端都会接触。在实际的项目开发中，webSocket在用于双向传输和推送消息方面能做到灵活、简便、高效，发挥着不可或缺的作用。
一、什么是webSocket
webSo
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/HTTP/">
                        <span class="chip bg-color">HTTP</span>
                    </a>
                    
                    <a href="/tags/WebSocket/">
                        <span class="chip bg-color">WebSocket</span>
                    </a>
                    
                    <a href="/tags/Ajax/">
                        <span class="chip bg-color">Ajax</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
